package com.tth.learn.addproperties.java;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 创建线程的方式三：实现Callable接口（JDK5.0新增）
 *
 * @Author tth
 * @Date 2022/11/3 17:37
 */
public class CreateThreadTest3 {
    public static void main(String[] args) {
        // 3.创建Callable实现类对象
        MyThreadByCallable mtc = new MyThreadByCallable();

        // 4.创建FutureTask对象
        FutureTask futureTask = new FutureTask(mtc);

        // 5.创建Thread对象，并启动线程
        new Thread(futureTask).start();

        try {
            // 6.获取call()中返回值
            Object o = futureTask.get();
            System.out.println(o);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

// 1.创建Callable的实现类
class MyThreadByCallable implements Callable {
    // 2.重写call()
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}
